package com.zzyl.intercept;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class SysUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private AntPathMatcher antPathMatcher=new AntPathMatcher();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求是不是接口
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取token
        String token = request.getHeader(Constants.USER_TOKEN);

        //判断token是否为空
        if(StringUtils.isEmpty(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //解析token
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        //判断数据是否为空
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        String userJson = claims.get("currentUser").toString();
        //转换为使用类型
        UserVo userVo = JSONUtil.toBean(userJson, UserVo.class);
        //从redis获取数据
        String key = CacheConstant.PUBLIC_ACCESS_URLS + userVo.getId();
        String urlJson = redisTemplate.opsForValue().get(key);
        List<String> urlList=null;
        if(!ObjectUtil.isEmpty(urlJson)){
            urlList=JSONUtil.toList(urlJson,String.class);
        }

        //鉴权 （当前访问路径和redis获取的集合路径进行对比）
        //获取当前访问路径
        String targetUrl = request.getMethod() + request.getRequestURI();

        for (String url : urlList) {
            if(antPathMatcher.match(url,targetUrl)){

                //共享数据存储到threadlocal中
                UserThreadLocal.setSubject(userJson);
                //直接放行
                return true;
            }
        }
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeSubject();
    }
}
